import {
  getListApi,
  getPageStaticApi,
  reverseBillApi,
  reverseChargeOffBillApi,
  statisticsDataApi,
  receivableBillExcelApi,
  receivableBillApi,
  customerBillItemExcelApi
} from "@/api/financialManagement/receivable/statement";
import CommonHook from "@/hook/commonHook";
import { message, Modal } from "ant-design-vue";
import dayjs from "dayjs";
import { Ref, computed, createVNode } from "vue";
import { ExclamationCircleOutlined } from "@ant-design/icons-vue";
export default function OperationHook(state: {
  searchForm: ReceivableStatement.SearchForm;
  tableData: Ref<ReceivableStatement.ListRows[]>;
  tableRef: Ref<any>;
  dialogOpts: Base.DialogOpts;
  drawerOpts: Base.DrawerOpts;
  loading: Ref<boolean>;
  activeKey: Ref<string>;
  pageStat: Ref<Base.GeneraDataType>;
}) {
  const { searchForm, tableData, drawerOpts, loading, tableRef, dialogOpts, activeKey, pageStat } = state;
  const selectRows = computed<Array<ReceivableStatement.ListRows>>(() => {
    return tableRef.value.xTable.getCheckboxRecords() || [];
  });
  const { downloadFileByBlob } = CommonHook();
  const getData = async () => {
    const params = {
      ...getParams()
    };
    loading.value = true;
    tableData.value = [];
    return getListApi(params)
      .then((res: any) => {
        const { code, data } = res;
        if (code === 200) {
          tableData.value = data.records || [];
          searchForm.beforePageNum = searchForm.pageNum;
          searchForm.total = Number(data.total);
        }
      })
      .finally(() => {
        loading.value = false;
      });
  };
  const getParams = () => {
    const { createByList, waybillNums, customerIdList, stateList, bizIdList, accountPeriodIdList, createTime, pageNum, pageSize, billNums, companyIdList } = searchForm;
    const params: any = {
      preOrderNoList: [],
      waybillNumList: [],
      fbaNumberList: [],
      bizIdList,
      customerIdList,
      stateList,
      accountPeriodIdList,
      createByList,
      createStartTime: createTime.length ? dayjs(createTime[0]).format("YYYY-MM-DD HH:mm:ss") : undefined,
      createEndTime: createTime.length ? dayjs(createTime[1]).format("YYYY-MM-DD HH:mm:ss") : undefined,
      pageNum,
      pageSize,
      chargeOffState: Number(activeKey.value),
      billNums,
      companyIdList
    };
    if (waybillNums)
      params.waybillNums = waybillNums
        .trim()
        .replace(/,{1,}|，{1,}|\+{1,}|\s{1,}/g, ",")
        .split(",");
    if (billNums) {
      params.billNums = billNums
        .trim()
        .replace(/,{1,}|，{1,}|\+{1,}|\s{1,}/g, ",")
        .split(",");
    } else {
      params.billNums = [];
    }

    if (searchForm.sort) {
      params.order = searchForm.order;
      params.sort = searchForm.sort;
    }

    return params;
  };
  const pageStateic = () => {
    const params = getParams();
    return getPageStaticApi({ ...params }).then((res: any) => {
      const { code, data } = res;
      if (code === 200) {
        Object.assign(pageStat.value, {
          0: data[0],
          1: data[1]
        });
        // activeKey.value = String(getNoZeroKey(pageStat.value, ["0", "1"]));
      }
    });
  };
  const searchHandle = async () => {
    searchForm.pageNum = 1;
    await pageStateic();
    getData();
  };
  const changeTabHandle = () => {
    getData();
  };
  // 修改备注
  const modifyRemarkHandle = (row: ReceivableStatement.ListRows) => {
    dialogOpts.title = `修改备注`;
    dialogOpts.width = "520px";
    dialogOpts.type = 1;
    dialogOpts.component = "ModifyRemark";
    dialogOpts.passData = row;
    dialogOpts.visible = true;
  };
  // 撤销账单
  const reverseBillHandle = (row: ReceivableStatement.ListRows) => {
    Modal.confirm({
      title: "是否撤销当前账单?",
      icon: createVNode(ExclamationCircleOutlined),
      onOk() {
        reverseBillApi([row.id]).then((res: any) => {
          const { code } = res;
          if (code === 200) {
            message.success("撤销成功!");
            searchHandle();
          }
        });
      }
    });
  };
  // 批量撤销账单
  const batchReverseBillHandle = () => {
    if (!selectRows.value.length) return message.error("请勾选账单!");
    Modal.confirm({
      title: "是否撤销勾选的账单?",
      icon: createVNode(ExclamationCircleOutlined),
      onOk() {
        reverseBillApi(selectRows.value.map((t: any) => t.id)).then((res: any) => {
          const { code } = res;
          if (code === 200) {
            message.success("撤销成功!");
            searchHandle();
          }
        });
      }
    });
  };
  // 核销账单
  const chargeOffBillHandle = (row: ReceivableStatement.ListRows) => {
    drawerOpts.title = `核销账单`;
    drawerOpts.width = "1200px";
    drawerOpts.type = 1;
    drawerOpts.component = "VerificationBill";
    drawerOpts.passData = [row];
    drawerOpts.visible = true;
  };
  // 批量核销账单
  const batchChargeOffBillHandle = () => {
    if (!selectRows.value.length) return message.error("请勾选账单!");
    const allCustomerId = Array.from(new Set(selectRows.value.map((t: any) => t.customerId)));
    if (allCustomerId.length > 1) return message.error("只能核销同一客户的账单!");
    const billType = Array.from(new Set(selectRows.value.map((t: any) => t.billType)));
    if (billType.length > 1) return message.error("账单类型不一致");

    drawerOpts.title = `核销账单`;
    drawerOpts.width = "1200px";
    drawerOpts.type = 2;
    drawerOpts.component = "VerificationBill";
    drawerOpts.passData = selectRows.value;
    drawerOpts.visible = true;
  };
  // 生成对账单
  const createBillHandle = () => {
    if (!selectRows.value.length) return message.error("请勾选至少一条费用！");
    dialogOpts.title = `生成对账单`;
    dialogOpts.width = "520px";
    dialogOpts.type = 1;
    dialogOpts.component = "CreateBill";
    dialogOpts.passData = selectRows.value;
    dialogOpts.visible = true;
  };
  // 修改客户备注
  const modifyInnerRemarkHandle = () => {
    if (!selectRows.value.length) return message.error("请勾选运单!");
    if (selectRows.value.length > 1) return message.error("只能勾选1条运单!");
    dialogOpts.title = `修改内部备注`;
    dialogOpts.width = "520px";
    dialogOpts.type = 2;
    dialogOpts.component = "ModifyRemark";
    dialogOpts.passData = selectRows.value[0];
    dialogOpts.visible = true;
  };
  // 反核销
  const reverseChargeOffBillHandle = (row: ReceivableStatement.ListRows) => {
    Modal.confirm({
      title: "是否反核销该账单?",
      icon: createVNode(ExclamationCircleOutlined),
      onOk() {
        reverseChargeOffBillApi({ id: row.id }).then((res: any) => {
          const { code } = res;
          if (code === 200) {
            message.success("操作成功!");
            searchHandle();
          }
        });
      }
    });
  };
  // 日志
  const showLogHandle = (row: ReceivableStatement.ListRows) => {
    drawerOpts.title = `账单日志`;
    drawerOpts.width = "1200px";
    drawerOpts.type = 1;
    drawerOpts.component = "OperationLog";
    drawerOpts.passData = [row];
    drawerOpts.visible = true;
  };
  // 批量账单日志
  const batchShowLogHandle = () => {
    if (!selectRows.value.length) return message.error("请勾选账单!");
    drawerOpts.title = `账单日志`;
    drawerOpts.width = "1200px";
    drawerOpts.type = 1;
    drawerOpts.component = "OperationLog";
    drawerOpts.passData = selectRows.value;
    drawerOpts.visible = true;
  };
  // 获取统计数据
  const getStatisticsDataFn = () => {
    const params: any = {
      ...getParams()
    };
    if (selectRows.value.length) params.list = selectRows.value;
    return statisticsDataApi(params).then((res: any) => {
      const { code, data } = res;
      if (code === 200) {
        dialogOpts.passData = data || {};
      }
    });
  };
  // 查看统计
  const showStatictisHandle = () => {
    dialogOpts.title = "查看统计";
    dialogOpts.width = "900px";
    dialogOpts.component = "DataStatistics";
    dialogOpts.visible = true;
  };
  //批量导出
  const downloadDataHandle = () => {
    const params = {
      ...getParams(),
      list: selectRows.value.length ? selectRows.value : undefined
    };

    return receivableBillExcelApi(params).then((res: any) => {
      const { code } = res;
      if (code === 200) {
        message.success("创建任务成功，请前往导出中心下载！");
      }
    });
  };
  //账单导出
  const billExportHandle = () => {
    const params = {
      ...getParams(),
      list: selectRows.value.length ? selectRows.value : undefined
    };
    return receivableBillApi(params).then((res: any) => {
      const { filename } = res.headers;
      const { data } = res;
      if (filename.split(".")[1] === "zip") {
        downloadFileByBlob(data, "应收对账单-总运费.zip");
      } else {
        const { companyName } = selectRows.value[0];
        downloadFileByBlob(data, `${companyName}-${dayjs().format("YYYYMMDDHHmmss")}-总运费.xlsx`);
      }
    });
  };

  //账单明细导出
  const billExportDetailHandle = () => {
    const params = {
      ...getParams(),
      list: selectRows.value.length ? selectRows.value : undefined
    };
    return customerBillItemExcelApi(params).then((res: any) => {
      const { filename } = res.headers;
      const { data } = res;
      if (filename.split(".")[1] === "zip") {
        downloadFileByBlob(data, "应收对账单-费用明细.zip");
      } else {
        const { companyName } = selectRows.value[0];
        downloadFileByBlob(data, `${companyName}-${dayjs().format("YYYYMMDDHHmmss")}-费用明细.xlsx`);
      }
    });
  };

  return {
    searchHandle,
    getData,
    modifyRemarkHandle,
    modifyInnerRemarkHandle,
    createBillHandle,
    changeTabHandle,
    reverseBillHandle,
    batchReverseBillHandle,
    chargeOffBillHandle,
    reverseChargeOffBillHandle,
    showLogHandle,
    batchShowLogHandle,
    batchChargeOffBillHandle,
    getStatisticsDataFn,
    showStatictisHandle,
    downloadDataHandle,
    billExportHandle,
    billExportDetailHandle
  };
}
